<?php

namespace App\Models\Product;

use App\Helpers\Code;
use App\Models\BaseModel;
use Illuminate\Support\Facades\Auth;

class ProjectProduct extends BaseModel
{
    protected $table = 'project_products';
    protected $fillable = [
        'project_id', 'product_id', 'case_total', 'money', 'special_remark', 'remark', 'created_by', 'updated_by', 'data_scope'
    ];

    public function product(){
        return $this->belongsTo('App\Models\Product\Product','product_id');
    }

    /*添加项目产品*/
    public function addProjectProduct($data)
    {
        $project = Project::find($data['project_id']);
        $product = Product::find($data['product_id']);
        if (!$project || !$product) {
            return null;
        }

        $model = $this->where(['product_id' => $data['product_id'], 'project_id' => $data['project_id']])->first();
        if($model){
            return Code::INSIDE_ERROR;
        }

        $userId = Auth::id();
        $data['created_by'] = $userId;
        $data['updated_by'] = $userId;
        $data['data_scope'] = $this->getDataScope();
        return $this->create($data);
    }

    /*删除项目包含产品*/
    public function deleteProjectProduct($id)
    {
        $model = $this->find($id);
        if (!$model) {
            return null;
        }

        return $model->delete();
    }

    /*获取指定项目包含全部产品*/
    public function getProjectProductAll($id){
        $model = $this->with(['product:id,title'])
            ->where('project_id',$id)
            ->select(['id','product_id','case_total','money','special_remark','remark'])
            ->get();
        return $model;
    }
}
